//放置我们和用户有关的状态管理
// createSlice 这个是一个配置user的仓库配置。
import { createSlice } from "@reduxjs/toolkit";
import { request } from "@/utils";
import { setToken as _setToken, getToken, removeToken } from "@/utils/index"
import { loginApi, getUserApi } from "@/apis/user";


const userStore = createSlice({
    name: 'user',
    initialState: {
        // 初始数据
        token: getToken() || '',
        userInfo: {},

    },
    reducers: {
        // 请求方法
        setToken(s, action) {
            s.token = action.payload
            _setToken(action.payload)

        },
        setUserInfo(s, action) {
            s.userInfo = action.payload
        },
        setGetOut(s) {
            s.token = ''
            s.userInfo = {}
            removeToken()
        }
    }
})

const { setToken, setUserInfo, setGetOut } = userStore.actions

// 编写异步方法
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        // const res = await request.post('/authorizations', loginForm)
        const res = await loginApi(loginForm)
        dispatch(setToken(res.data.token))
    }
}
// 编写请求个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        // const res = await request.get('/user/profile')
        const res = await getUserApi()
        dispatch(setUserInfo(res.data))
        console.log(res.data);
    }
}
// 这里写清登录信息
const fetchGetOut = () => {
    return async (dispatch) => {
        dispatch(setGetOut())
        // console.log(res.data);
    }
}

const userReducer = userStore.reducer

// 解构一下方法
export { setToken, fetchLogin, fetchUserInfo, fetchGetOut }

export default userReducer

